const fs = require('fs-extra')
const path = require('path')

function ImportFilePlugin(options) {
    this.srcpath = options.srcpath
    this.destpath = options.destpath
    this.name = options.name
    this.template = options.template
    // 使用配置（options）设置插件实例
}

ImportFilePlugin.prototype.apply = function(compiler) {
    const _this = this
    const src = path.resolve(_this.srcpath, _this.name)
    const dest = path.resolve(_this.destpath, _this.name)
    console.log(dest)
    compiler.plugin('after-emit', function(compilation) {
        //复制文件
        fs.pathExists(src, function(err) {
            if (err) {
                console.log("source is not exist")
            } else {
                fs.copy(src, dest, function(err) {
                    if (err) {
                        console.log(err)
                        return
                    } else {
                        console.log("success!")
                    }
                });
            }
        })
        //插入脚本
        const script = " <script type='javascript' src='" + _this.template + "'></script> "
        console.log(insertStr(script, '<body/>'))
        fs.readFile(path.resolve(_this.destpath, _this.template), 'utf8', function(err, htmlcontent) {
            if (err) {
                console.log(err)
            } else {
                console.log(htmlcontent)
            }
        })
    })
    compiler.plugin('done', function() {

    })
};

function insertStr(str, flag) {
    const start = str.indexOf(flag)
    const length = flag.length
    for (var i = start; i < start + length; i++) {
        str[i] = flag[i - start]
    }
    return str
}

module.exports = ImportFilePlugin;